<template>
  <div class="carousel" @mouseenter="pause" @mouseleave="start">
    <!-- 左切换按钮 -->
    <button class="carousel-button carousel-button-prev" @click="prev">
      <span>&lt;</span>
    </button>

    <!-- 轮播图容器 -->
    <div class="carousel-container" :style="containerStyle">
      <div v-for="(item, index) in images" :key="index" class="carousel-item">
        <img  :src="item" alt="" />
      </div>
    </div>

    <!-- 右切换按钮 -->
    <button class="carousel-button carousel-button-next" @click="next">
      <span>&gt;</span>
    </button>

    <!-- 指示器 -->
    <div class="carousel-indicators">
      <span
          v-for="(_item, index) in images"
          :key="index"
          :class="{ active: currentIndex === index }"
          @click="goTo(index)"
      ></span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";

const props = defineProps<{
  images: string[];
}>();

const currentIndex = ref(0);
const intervalId = ref<number | null>(null);

const containerStyle = ref({
  transform: `translateX(0)`,
});

// 跳转到指定索引
const goTo = (index: number) => {
  currentIndex.value = index;
  containerStyle.value.transform = `translateX(${-index * 100}%)`;
};

// 下一张
const next = () => {
  const nextIndex = (currentIndex.value + 1) % props.images.length;
  goTo(nextIndex);
};

// 上一张
const prev = () => {
  const prevIndex = (currentIndex.value - 1 + props.images.length) % props.images.length;
  goTo(prevIndex);
};

// 开始自动播放
const start = () => {
  if (intervalId.value) return;
  intervalId.value = setInterval(next, 3000); // 自动播放间隔
};

// 暂停自动播放
const pause = () => {
  if (intervalId.value) {
    clearInterval(intervalId.value);
    intervalId.value = null;
  }
};

onMounted(start);
onUnmounted(() => {
  if (intervalId.value) {
    clearInterval(intervalId.value);
  }
});
</script>

<style scoped>
.carousel {
  position: relative;
  width: 100%;
  overflow: hidden;
}

.carousel-container {
  display: flex;
  transition: transform 0.5s ease-in-out;
}

.carousel-item {
  flex-shrink: 0;
  width: 100%;
}

.carousel-item img {
  width: 100%;
  height: auto;
  display: block;
}

.carousel-indicators {
  position: absolute;
  bottom: 10px;
  width: 100%;
  text-align: center;
}

.carousel-indicators span {
  display: inline-block;
  width: 10px;
  height: 10px;
  margin: 0 5px;
  background-color: #ccc;
  border-radius: 50%;
  cursor: pointer;
}

.carousel-indicators span.active {
  background-color: #ff6600;
}

/* 切换按钮样式 */
.carousel-button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  cursor: pointer;
  font-size: 24px;
  padding: 10px;
  z-index: 10;
}

.carousel-button-prev {
  left: 10px;
}

.carousel-button-next {
  right: 10px;
}
</style>